package com.baozun.houji.order.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.CountDownTimer
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.baozhun.mall.common.arouter.RoutePath
import com.baozhun.mall.common.base.BaseActivity
import com.baozhun.mall.common.ext.showToast
import com.baozhun.mall.common.model.bean.ExpressInfoBean
import com.baozhun.mall.common.model.enums.OrderStatus
import com.baozhun.mall.common.util.Constants
import com.baozun.houji.order.R
import com.baozun.houji.order.databinding.ActivityOrderDetailBinding
import com.baozun.houji.order.util.order.OrderActionFinishListener
import com.baozun.houji.order.util.order.OrderActionManager
import com.baozun.houji.order.util.order.enums.OrderActionType
import com.baozun.houji.order.util.order.enums.OrderSource
import com.baozun.houji.order.viewmodel.OrderDetailViewModel
import com.blankj.utilcode.util.IntentUtils
import com.jaeger.library.StatusBarUtil
import me.hgj.jetpackmvvm.ext.util.copyToClipboard

/**
 * @Title：订单详情页
 * @Description：
 * @Author：xing.luo
 * @Since：2022/11/20
 * @Version：1.0.0
 */
@Route(path = RoutePath.Order.ORDER_DETAIL)
class OrderDetailActivity : BaseActivity<OrderDetailViewModel, ActivityOrderDetailBinding>(), OrderActionFinishListener {
    private var mTimer: CountDownTimer? = null
    private val mOrderId by lazy { intent.getStringExtra(Constants.Order.ORDER_ID).toString() }

    companion object {
        fun start(context: Context, orderId: String?) {
            var intent = Intent(context, OrderDetailActivity::class.java)
            intent.putExtra(Constants.Order.ORDER_ID, orderId)
            context.startActivity(intent)
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.setColor(this, getColor(android.R.color.transparent))
        StatusBarUtil.setTransparentForImageView(this, mDataBinding.titleBar)
    }

    override fun onResume() {
        super.onResume()
        mViewModel.requestData(mOrderId)
        mViewModel.getLogisticsInfo(mOrderId)
    }

    override fun createObserver() {
        super.createObserver()

        mViewModel.mOrderDetailBean.observe(this) {
            OrderActionManager.getInstance(
                mOrderId,
                it.after_sale_no.toString(),
                it.order_status,
                it.after_sale_status,
                orderSource = OrderSource.ORLDER_DETAIL,
                it.pay_amount,
                actionResultListener = this
            ).addActionBt(mDataBinding.llAction)
            //待支付启动倒计时
            if (it.order_status == OrderStatus.WAIT_DELIVERY.status && it.pay_expire_time > 0 ||
                it.order_status == OrderStatus.WAIT_RECEIVE.status && it.finish_expire_time > 0
            ) {
                var countdownTime = if (it.order_status == OrderStatus.WAIT_DELIVERY.status) it.pay_expire_time else it.finish_expire_time
                startCountDownTimer(countdownTime * 1000)
            }
        }

        mViewModel.mExpressInfoBean.observe(this) {

        }
    }

    override fun onClick(v: View?) {
        super.onClick(v)
        when (v?.id) {
            R.id.tv_copy -> {
                copyToClipboard(mViewModel.mOrderDetailBean.value?.order_no)
                showToast(com.baozhun.mall.res.R.string.alr_copy)
            }

            R.id.tv_call_phone -> {
                startActivity(IntentUtils.getDialIntent(mViewModel.mExpressInfoBean.value?.express_phone.toString()))
            }

            R.id.tv_expire_num, R.id.tv_express_name, R.id.iv_express_logo -> { //复制物流单号
                copyToClipboard(mViewModel.mExpressInfoBean.value?.express_no)
                showToast(com.baozhun.mall.res.R.string.alr_copy)
            }

            R.id.cl_logistics_info -> { //物流详情
                showLogisticsInfo()
            }

            R.id.tv_apply_refund -> { //申请售后
                if (mViewModel.mOrderDetailBean.value?.isExceedRefundTimeLimit() == true) {
                    showToast(com.baozhun.mall.res.R.string.exceed_refund_time_limit_hint)
                } else if (mViewModel.mOrderDetailBean.value?.enableRefund() == true) {
                    ApplyRefundActivity.start(this, mOrderId, mViewModel.mOrderDetailBean.value?.order_status == OrderStatus.WAIT_SEND.status)
                } else {
                    RefundDetailActivity.start(this, mViewModel.mOrderDetailBean.value?.after_sale_no)
                }
            }

        }
    }

    override fun reload(orderActionType: OrderActionType?) {
        mViewModel.requestData(mOrderId)
    }

    override fun showLogisticsInfo() {
        LogisticsDetailActivity.start(this, arrayListOf<ExpressInfoBean?>().apply {
            add(mViewModel.mExpressInfoBean.value)
        }, true)
    }

    /**
     * 开始倒计时
     */
    private fun startCountDownTimer(payExpireTime: Long) {
        if (payExpireTime <= 0) return
        mViewModel.mSurplusTime.value = payExpireTime
        mTimer?.cancel()
        mTimer = object : CountDownTimer(payExpireTime, 1000L) {
            override fun onTick(millisUntilFinished: Long) {
                mViewModel.mSurplusTime.value?.let {
                    mViewModel.mSurplusTime.value = it - 1000
                }
            }

            override fun onFinish() {
                mViewModel.requestData(mOrderId)
            }

        }
        mTimer?.start()
    }

    override fun onDestroy() {
        super.onDestroy()
        mTimer?.cancel()
    }
}